#include "IndexedShapeShower.h"
#include "Util.h"
#include <QPainter>

IndexedShapeShower::IndexedShapeShower(const std::shared_ptr<IPalette> &pal, QWidget *parent) : QWidget(parent)
{
    palette = pal;
    spinBox = new QSpinBox(this);
    spinBox->setMaximum(1);
    spinBox->setMinimum(1);

    connect(spinBox, &QSpinBox::editingFinished, [=]()
    {
        index = spinBox->value() - 1;
        if (shp != nullptr)
        {
            auto &frame = shp->frames[index];
            img = QPixmap::fromImage(Util::BuildQImage(*frame.data, frame.width, frame.height, *palette));
            repaint();
        }
    });

    spinBox->setFixedHeight(32);
    setFixedSize(256, 256 + 32);
    spinBox->move(0, 256);
}

void IndexedShapeShower::SetPalette(const std::shared_ptr<IPalette>& pal)
{
    palette = pal;
    auto &frame = shp->frames[index];
    img = QPixmap::fromImage(Util::BuildQImage(*frame.data, frame.width, frame.height, *palette));
    repaint();
}

void IndexedShapeShower::SetShp(const std::shared_ptr<Shp>& shp_)
{
    shp = shp_;
    index = 0;
    spinBox->setMaximum(shp_->header.frameTotal);
    spinBox->setMinimum(1);
    setFixedSize(shp_->header.width, shp_->header.height + 32);
    spinBox->setFixedWidth(shp_->header.width);
    spinBox->move(0, shp_->header.height);
    auto &frame = shp->frames[index];
    img = QPixmap::fromImage(Util::BuildQImage(*frame.data, frame.width, frame.height, *palette));
    repaint();
}

void IndexedShapeShower::paintEvent(QPaintEvent *e)
{
    QPainter pp(this);
    auto c = palette->GetColor(0);
    auto backColor = QColor(c.r, c.g, c.b, c.a);
    if (shp == nullptr)
    {
        pp.fillRect(QRect(0, 0, 256, 256), backColor);
    }
    else
    {
        auto& frame = shp->frames[index];
        pp.fillRect(QRect(0, 0, shp->header.width, shp->header.height), backColor);
        pp.drawPixmap(QRect(frame.x, frame.y, frame.width, frame.height), img);
    }
    QWidget::paintEvent(e);
}
